package com.wusuowei.config;

import com.wusuowei.config.exception.CustomAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
// 标识为资源服务器, 所有发往当前服务的请求，都会去请求头里找token，找不到或验证不通过不允许访问
@EnableResourceServer
//开启方法级别权限控制
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //配置当前资源服务器的ID
    private static final String RESOURCE_ID = "wusuowei";

    @Autowired
    private TokenStore tokenStore;


    /**当前资源服务器的一些配置, 如资源服务器ID **/
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        // 配置当前资源服务器的ID, 会在认证服务器验证(客户端表的resources配置了就可以访问这个服务)
        resources.resourceId(RESOURCE_ID)
                //TODO 可以把配置文件的security配置整个去掉，也要把启动类的@EnableOAuth2Sso注解去掉，不然会报错
                // 在本地配置一个TokenConfig，跟认证服务器一样的类，进行本地token校验
                .tokenStore(tokenStore);
        CustomAuthenticationEntryPoint customAuthenticationEntryPoint = new CustomAuthenticationEntryPoint();
        resources.authenticationEntryPoint(customAuthenticationEntryPoint);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                //不创建session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()

                .authorizeRequests()
                .antMatchers("/auth/register","/auth/check","/auth/getPublicKey","/oauth/token","/auth/oauth/**","/checkcode/**").permitAll() //不进行认证的url
                .anyRequest().authenticated();//所有请求都必须认证才能访问，必须登录
        //http.addFilterAfter(new GatewayAuthFilter(), HeaderWriterFilter.class);
    }

}